package com.xp.code.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

public class CommonUtils {

	/**
	 * 根据传入的SQL语句获取分页SQL语句
	 * 
	 * @param startIndex
	 *            开始索引
	 * @param endIndex
	 *            结束索引
	 * @param strSql
	 *            传入的SQL语句
	 * @return 返回的SQL语句
	 * @throws Exception
	 */
	public static String getPageSql(int startIndex, int endIndex, String strSql)
			throws Exception {
		if (startIndex > endIndex) {
			throw new Exception("分页获取数据时开始索引不能大于结束索引");
		}
		if (startIndex == -1 && endIndex == -1) {
			return strSql;
		} else {
			StringBuffer sb = new StringBuffer("SELECT (SELECT COUNT(1) FROM (");
			sb.append(strSql);
			sb.append(")) totolnum,b.* FROM (SELECT A.*, rownum rn FROM (");
			sb.append(strSql);
			sb.append(") A WHERE rownum <=");
			sb.append(endIndex);
			sb.append(") B WHERE rn >=");
			sb.append(startIndex);
			return sb.toString();
		}
	}

	/**
	 * 转换字符串中的'至''
	 * 
	 * @param str
	 * @return
	 */
	public static String parseSql(String str) {
		char token = '\'';

		if (str.indexOf(token) == -1) {
			return str;
		}

		StringBuffer newStr = new StringBuffer();

		int len = str.length();
		for (int i = 0; i < len; i++) {
			if (str.charAt(i) == token) {
				newStr.append("''");
			} else {
				newStr.append(str.charAt(i));
			}
		}

		return newStr.toString();
	}

	/**
	 * 创建唯一UUID
	 */
	public static String getUUID() {
		UUID id = UUID.randomUUID();
		return id.toString().toUpperCase();
	}
	
	/**
	 * 根据传入的SQL语句得到获取总记录数的Sql语句
	 * @param strSql 传入的SQL语句
	 * @return 返回的SQL语句
	 * @throws Exception
	 */
	public static String getTotalCountSql(String strSql) throws Exception
	{
		StringBuffer sb = new StringBuffer("SELECT COUNT(1) FROM (");
		sb.append(strSql);
		sb.append(")");
		return sb.toString();
	}
	
	/**
	 * 根据日期与格式得到规定格式的日期字符串
	 * @param date
	 * @param strFormat
	 * @return
	 */
	public static String parseDatetoString(Date date, String strFormat)
	{
		SimpleDateFormat f = new SimpleDateFormat(strFormat);
		try
		{
			return f.format(date);
		}
		catch (Exception ex)
		{
			f = new SimpleDateFormat("yyyy-MM-dd");
			return f.format(date);
		}
	}

	public static String parseDatetoString(Date date)
	{
		return parseDatetoString(date, "yyyy-MM-dd");
	}

	public static String parseDatetoString(Calendar cal)
	{
		return parseDatetoString(cal, "yyyy-MM-dd");
	}

	public static String parseDatetoString(Calendar cal, String strFormat)
	{
		return parseDatetoString(cal.getTime(), strFormat);
	}

	public static void main(String args[]) throws Exception {
		System.out.println(CommonUtils.getUUID());
	}
}
